<?php

namespace app\models;

/**
 * 解决命令行模式下MySQL会出现`MySQL server has gone away`
 * Class DbCommand
 * @package app\models
 */
class DbCommand extends \yii\db\Command
{
    /**
     * @inheritdoc
     */
    public function execute()
    {
        try {
            return parent::execute();
        } catch (\yii\db\Exception $e) {
            if ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013) {
                $this->db->close();
                $this->db->open();
                $this->pdoStatement = null;
                return parent::execute();
            } else {
                throw $e;
            }
        }
    }

    /**
     * @inheritdoc
     */
    protected function queryInternal($method, $fetchMode = null)
    {
        try {
            return parent::queryInternal($method, $fetchMode);
        } catch (\yii\db\Exception $e) {
            if ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013) {
                $this->db->close();
                $this->db->open();
                $this->pdoStatement = null;
                return parent::queryInternal($method, $fetchMode);
            } else {
                throw $e;
            }
        }
    }
}
